package com.love.cloud.common.security.component;


import com.love.cloud.common.security.service.MyUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 自定义资源服务token处理器
 * @author lengleng
 * @date 2020/9/29
 */
@Primary
@Service
public class MyResourceServerTokenServices implements ResourceServerTokenServices {
	protected final Log logger = LogFactory.getLog(this.getClass());
	@Resource
	private TokenStore tokenStore;

	private RemoteTokenServices remoteTokenServices;

	public RemoteTokenServices getRemoteTokenServices() {
		return remoteTokenServices;
	}

	public void setRemoteTokenServices(RemoteTokenServices remoteTokenServices) {
		this.remoteTokenServices = remoteTokenServices;
	}

	@Override
	public OAuth2Authentication loadAuthentication(String accessToken)
			throws AuthenticationException, InvalidTokenException {
		OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(accessToken);
		if (oAuth2Authentication == null) {
			return null;
		}

		if (oAuth2Authentication.getPrincipal() instanceof MyUser) {
			return oAuth2Authentication;
		}
		//如果从tokenStore中没有获取到就走原来默认的
		return remoteTokenServices.loadAuthentication(accessToken);
	}

	@Override
	public OAuth2AccessToken readAccessToken(String accessToken) {
		throw new UnsupportedOperationException("Not supported: read access token");
	}

}
